package com.tdcy.sys.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import net.sf.ehcache.Element;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tdcy.sys.dao.IMenuDAO;
import com.tdcy.sys.dao.IRoleMenusDAO;
import com.tdcy.sys.dao.eo.MenuEO;
import com.tdcy.sys.service.IMenuSvc;
import com.tdcy.sys.service.ISeqNoSvc;
import com.tdcy.sys.util.EhcacheUtils;

@Service
public class MenuSvcImpl implements IMenuSvc {
	@Resource
	IMenuDAO menuDAO;

	@Resource
	IRoleMenusDAO rolesmenuDAO;

	@Resource
	ISeqNoSvc seqSvc;

	public List<MenuEO> getAllMenu() {
		Object obj = EhcacheUtils.getCache("appCache", "allmenu");
		List<MenuEO> list = null;
		if(obj!=null){
			Element el = (Element) obj;
			list = (List<MenuEO>) el.getObjectValue();
		}else{
			list = menuDAO.findTableRecords(MenuEO.class);
		}
		
		List<MenuEO> tlist = new ArrayList<MenuEO>();
		for (MenuEO me : list) {
			if (me.getMenuType().compareTo(1) == 0 ) {
				tlist.add(me);
			}
		}
		EhcacheUtils.setCache( "appCache", "allmenu", tlist);
		return tlist;
	}
	

	public List<MenuEO> getAllRight() {
		Object obj = EhcacheUtils.getCache("appCache", "allright");
		List<MenuEO> list = null;
		if(obj!=null){
			Element el = (Element) obj;
			list = (List<MenuEO>) el.getObjectValue();
		}else{
			list = menuDAO.findTableRecords(MenuEO.class);
		}
		List<MenuEO> tlist = new ArrayList<MenuEO>();

		for (MenuEO me : list) {
			if (me.getMenuType().compareTo(2) == 0) {
				tlist.add(me);
			}
		}
		EhcacheUtils.setCache( "appCache", "allright", tlist);
		return tlist;
	}

	public MenuEO getMenuInfo(Integer menuid) {
		return menuDAO.findByPrimaryKey(MenuEO.class, menuid);
	}

	@Override
	public MenuEO updateMenu(MenuEO menu) {
		EhcacheUtils.removeCache("appCache", "allright");
		EhcacheUtils.removeCache("appCache", "allmenu");
		MenuEO meo = menuDAO.update(menu);
		return meo;
	}

	@Transactional
	public MenuEO addMenu(MenuEO menu) {
		menu.setMenuId(seqSvc.getMaxNo("menu_id"));
		menu.setLogFlag(1);
		menu.setValidFlag(1);

		MenuEO meo = menuDAO.save(menu);

		EhcacheUtils.removeCache("appCache", "allright");
		EhcacheUtils.removeCache("appCache", "allmenu");

		return meo;
	}

	@Override
	public boolean delMenu(Integer menuid) {
		boolean flag = menuDAO.deleteByPrimaryKey(MenuEO.class, menuid);
		EhcacheUtils.removeCache("appCache", "allright");
		EhcacheUtils.removeCache("appCache", "allmenu");
		return flag;
	}
	
	@Override
	public List<MenuEO> getAllMenusByRoleId(Integer roleid) {
		return rolesmenuDAO.getAllMenusByRoleId(roleid);
	}
	
	@Override
	public List<MenuEO> getAllRightsByRoleId(Integer roleid) {
		return rolesmenuDAO.getAllRightsByRoleId(roleid);
	}

}
